/**
 * Created by kevin on 17/4/5.
 */
var Router = require('koa-router')
var BasicAuth = require('../../util/BasicAuth')
var UserService = require('../../services/controllers/user.ctrl')
var SysService = require('../../services/controllers/sys.ctrl')
var ApiService = require('../../services/controllers/apiproxy.ctrl')

function register(app) {
    var router = new Router({
        prefix: '/manage'
    });

    router.get('/', function *(next) {
        this.body = 'welcome to manage site'
    });
    router.get('/login', function *(next) {
        this.body = 'welcome to login site'
    }).post('/login', function *(next) {
        var socketid = this.request.headers["socket-id"]
        var uid = this.request.body.uid;
        if(!uid) {
            // io.to(socketid).emit('notify', {
            //     message: '登录失败,请输入用户名',
            //     type: 'error',
            //     duration: 2000
            // });
            return this.body = RES.ERROR({}, '成功返回系统信息', 200)
        }
        var pwd = this.request.body.pwd;
        var sysname = this.request.body.sys;

        var sys = yield * SysService.findSwitchOn();
        console.log('this is sys', sys)

        var promises = [];
        for(let i=0; i < sys.rows.length; i++) {
            var sysObj = {};
            if(sys.rows[i]['name'] == 'hc-sales') {
                // sales 验证
                var token;
                try {
                    token = yield *ApiService.getToken(sys.rows[i]['url'], uid, pwd);
                    if(token) {
                        if(token.statusCode == 200) {
                            //登录成功
                            var domain = sys.rows[i]['url'].replace(/((http|ftp|https):\/\/)/g, '');
                            var sessionIdReg = /x\-pond\-sessionid=(\w+)\;/
                            token.headers['set-cookie'][0].replace(sessionIdReg, '');
                            var sessionId = RegExp.$1;

                            // console.log(sessionId, domain, 'this is sessionid')
                            // this.cookies.set('x-pond-sessionid', sessionId, {
                            //     domain: domain,
                            //     path: '/'
                            // })
                            //
                            // this.cookies.set('x-pond-sessionid', sessionId)

                            sysObj['status'] = 0;
                            sysObj['domain'] = domain;
                            sysObj['session_id'] = sessionId;
                            sysObj['authorize'] = token.body;
                            // var users = yield *ApiService.getUsers(token.body);
                            // console.log(users, 'these are users!');
                        }else {
                            // 登录失败 用户名密码错误
                            sysObj['status'] = 1;
                            sysObj['err'] = token.body;
                        }
                    }else {
                        sysObj['status'] = 2;
                    }
                }catch (e) {
                    sysObj['status'] = 2;
                    sysObj['err'] = e;
                }
                sysObj['name'] = sys.rows[i]['name'];
                sysObj['url'] = sys.rows[i]['url'];
                sysObj['uid'] = uid;
                sysObj['pwd'] = pwd;
                promises.push(sysObj);

                if(sysname == 'hc-sales') {
                    promises = [];
                    promises.push(sysObj);
                    return this.body = RES.SUCCESS(promises, '成功返回系统信息', 200)
                }
            }else if(sys.rows[i]['name'] == 'hc-crm') {
                var token;
                try {
                    var basicauth = BasicAuth(uid, pwd)
                    token = yield *ApiService.loginCRM(sys.rows[i]['url'], basicauth)
                    console.log(token , 'this is token!!!!!!' ,sysname)
                    if(token.statusCode == '200') {
                        sysObj['status'] = 0;
                        sysObj['authorize'] = basicauth;
                    }else if(token.statusCode == '401') {
                        sysObj['status'] = 1;
                        sysObj['err'] = 'unauthorized';
                    }
                } catch (e){
                    sysObj['status'] = 2;
                    sysObj['err'] = e;
                }

                sysObj['name'] = sys.rows[i]['name'];
                sysObj['url'] = sys.rows[i]['url'];
                sysObj['uid'] = uid;
                sysObj['pwd'] = pwd;
                promises.push(sysObj);

                if(sysname == 'hc-crm') {
                    promises = [];
                    promises.push(sysObj);
                    return this.body = RES.SUCCESS(promises, '成功返回系统信息', 200)
                }
            }
        }
        console.log(promises)

        return this.body = RES.SUCCESS(promises, '成功返回用户信息', 200)
    });
    router.post('/login1', function *(next) {

        var socketid = this.request.headers["socket-id"]
        var uid = this.request.body.uid;
        if(!uid) {
            io.to(socketid).emit('notify', {
                message: '登录失败,请输入用户名',
                type: 'error',
                duration: 2000
            });
            return this.body = ''
        }
        var pwd = this.request.body.pwd;
        var sys = yield * SysService.findSwitchOn();
        var promises = [];
        for(let i=0; i < sys.rows.length; i++) {
            var sysObj = {};

            var token;
            try {
                token = yield *ApiService.getToken(sys.rows[i]['url'], uid, pwd);
                if(token) {
                    if(token.statusCode == 200) {
                        //登录成功
                        var domain = sys.rows[i]['url'].replace(/((http|ftp|https):\/\/)/g, '');
                        var sessionIdReg = /x\-pond\-sessionid=(\w+)\;/
                        token.headers['set-cookie'][0].replace(sessionIdReg, '');
                        var sessionId = RegExp.$1;
                        var users;
                        var jwt = token.body;
                        // try {
                        //      users = yield *ApiService.getUsers(jwt, sessionId);
                        // }catch (e) {
                        //     console.log(e, 'this is e');
                        // }

                        console.log(users, 'this is userservices users!')


                        // console.log(sessionId, domain, 'this is sessionid')
                        // this.cookies.set('x-pond-sessionid', sessionId, {
                        //     domain: domain,
                        //     path: '/'
                        // })
                        //
                        // this.cookies.set('x-pond-sessionid', sessionId)

                        sysObj['status'] = 0;
                        sysObj['domain'] = domain;
                        sysObj['session_id'] = sessionId;
                        sysObj['authorize'] = jwt;
                        // var users = yield *ApiService.getUsers(token.body);
                        // console.log(users, 'these are users!');
                    }else {
                        // 登录失败 用户名密码错误
                        sysObj['status'] = 1;
                        sysObj['authorize'] = token.body;
                    }
                }else {
                    sysObj['status'] = 2;
                }
            }catch (e) {
                sysObj['status'] = 2;
                sysObj['authorize'] = e;
            }
            sysObj['name'] = sys.rows[i]['name'];
            sysObj['url'] = sys.rows[i]['url'];

            promises.push(sysObj);
        }

        this.body = ''
    });

    // router.post('/usersync', function *(next){
    //     var uid = this.request.body.uid;
    //     var pwd = this.request.body.pwd;
    //     var sys = this.request.body.sys;
    //     if(!sys) {
    //         // 同步所有系统
    //         var sales = yield *UserService.checkUser(uid, pwd, 'sales');
    //         var insurance = yield *UserService.checkUser(uid, pwd, 'insurance');
    //
    //         console.log(sales, insurance, 'this is sales and insurances');
    //         if(sales && insurance) {
    //             // 全部验证成功,设置新的系统统一登录账号
    //             // var abc = yield *UserService.syncUser(uid, pwd);
    //             return this.body = RES.SUCCESS({sales:sales,insurance: insurance, status: 2}, '返回系统密码验证结果', 200);
    //         }else if(sales || insurance){
    //             return this.body = RES.ERROR({sales:sales,insurance: insurance, status: 3}, '返回系统密码验证结果', 200);
    //         }else {
    //             return this.body = RES.ERROR({sales:sales,insurance: insurance, status: 4}, '返回系统密码验证结果', 200)
    //         }
    //     }
    //     var rs = yield *UserService.checkUser(uid, pwd, sys);
    //     // 单个信息验证结果
    //     var tmpJson = {};
    //     tmpJson[sys] = rs;
    //     tmpJson['status'] = 5;
    //     return this.body = RES.SUCCESS(tmpJson,'返回'+sys+'系统验证结果', 200);
    // })
    //
    // router.post('/unitinfo', function *(next) {
    //     var facadeUser = this.request.body.user;
    //     var rs = yield *UserService.unitInfo(facadeUser);
    //     return this.body = RES.SUCCESS(rs,'同步账号成功', 200);
    // })

    app.use(router.routes());
    app.use(router.allowedMethods());
}

module.exports = register;